package org.samcolon.eeexplore.hutool;

import cn.hutool.core.lang.Console;
import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * @Description: AES加密解密
 * @author: Sam.zhang
 * @date: 2021.09.03
 */

public class AES {

    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    private static String iv = "1234567890123456";//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
    private static String Algorithm = "AES";
    private static String AlgorithmProvider = "AES/CBC/PKCS7Padding"; //算法/模式/补码方式

    public static void main(String[] args) {
        try {
            // 密钥必须是16的倍数
            String keyStr = "yh2020123abcdefg";

            byte key[] = keyStr.getBytes("utf-8");//hexStringToBytes("0123456789ABCDEF");
            String src = "y1ha0_@##@aplus";
            Console.log("密钥原文:{}", keyStr);
//            Console.log("密钥:"+byteToHexString(key));
            Console.log("原字符串:" + src);

            SymmetricCrypto symmetricCrypto = new SymmetricCrypto("AES/CBC/PKCS7Padding", KeyUtil.generateKey(SymmetricAlgorithm.AES.getValue(), key), new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
            Console.log("hutool 加密：{}", symmetricCrypto.encryptBase64(src));
            Console.log("hutool 解密：{}", symmetricCrypto.decryptStr("iuJD8Yus5OBTYtQeNDF5Iw=="));

//            Console.log("Base64字符串:"+ Base64.encodeBase64String(src.getBytes(StandardCharsets.UTF_8)));

//            new cn.hutool.crypto.symmetric.AES("AES/CBC/PKCS7Padding", KeyUtil.generateKey(SymmetricAlgorithm.AES.getValue(), keyStr), (SecretKey) new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));


//            String enc = byteToHexString(encrypt(src, key));
//            Console.log("加密："+enc);
//            Console.log("Base64加密：{}", Base64.encodeBase64String(enc.getBytes(StandardCharsets.UTF_8)));
//            Console.log("解密："+new String(decrypt(enc, key), "utf-8"));
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] generatorKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
        keyGenerator.init(256);//默认128，获得无政策权限后可为192或256
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    public static IvParameterSpec getIv() throws UnsupportedEncodingException {
        Console.log("原偏移量：{}", iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
        Console.log("偏移量：{}", byteToHexString(ivParameterSpec.getIV()));
        return ivParameterSpec;
    }

    public static byte[] encrypt(String src, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);
        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
        return cipherBytes;
    }

    public static byte[] decrypt(String src, byte[] key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);

        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] hexBytes = hexStringToBytes(src);
        byte[] plainBytes = cipher.doFinal(hexBytes);
        return plainBytes;
    }

    /**
     * 将byte转换为16进制字符串
     *
     * @param src
     * @return
     */
    public static String byteToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串装换为byte数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return b;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


}
